<template>
	<view class="deviceAllocation-container">
		<!-- 自定义导航栏 -->
		<u-navbar title="设备下拨" :border-bottom="false" title-size="28" :background="{ background: 'transprant' }" back-icon-color="#fff" title-color="#fff">
			<view slot="right" class="right">
				<text @click="toAllocationRecord" style="color: #fff; font-size: 28rpx">下拨记录</text>
			</view>
		</u-navbar>

		<!-- 背景图片 -->
		<image src="@/static/deviceAllocation/deviceAllocation-bg.png" class="page-bg"></image>

		<!-- 页面数据主体 -->
		<view class="container-body">
			<!-- 数据统计盒子 -->
			<view class="dataBox">
				<!-- 更新时间 -->
				<view class="dataUpdateTimeBox">
					<view class="updateTime">数据更新时间：{{ updateTime }}</view>
					<view class="dataTips">
						<!-- <image src="" class="icon-help" /> -->
					</view>
				</view>
				<!-- 数据信息 -->
				<view class="dataInfoBox">
					<view class="left">
						<view class="label">已下拨机柜数</view>
						<view class="testNum">{{ AllocationData.boxCount }}</view>
					</view>
					<view class="right">
						<view class="label">已下拨充电宝数</view>
						<view class="testNum">{{ AllocationData.singleCount }}</view>
					</view>
				</view>
			</view>

			<!-- 巡检员选择项 -->
			<view @click="toChoose('巡检员')" class="chooseItem">
				<view class="item-title">巡检员</view>
				<view class="currentChoose">
					<text v-if="chooseInspector.id" class="coverText">{{ chooseInspector.userName }}</text>
					<text v-else class="coverText">请选择巡检员</text>
					<image class="goIcon" src="@/static/go-icon.png" />
				</view>
			</view>
			<!-- 设备选择项 -->
			<view @click="toChoose('设备类型')" class="chooseItem">
				<view class="item-title">设备类型</view>
				<view class="currentChoose">
					<text v-if="currentChooseDeviceType.value" class="coverText">{{ currentChooseDeviceType?.value == 'device' ? '机柜' : '充电宝' }}</text>
					<text v-else class="coverText">请选择设备类型</text>
					<image class="goIcon" src="@/static/go-icon.png" />
				</view>
			</view>

			<!-- 选择的设备列表 -->
			<view v-if="currentChooseDeviceType.value == 'device' && chooseDeviceList.length > 0" class="choose-list-box">
				<view v-for="(item, index) in chooseDeviceList" :key="index" class="chooseListItem">
					<view class="brief_info">
						<view class="brief_info_text">
							<text>{{ currentChooseDeviceType.value == 'device' ? '机柜SN：' : '充电宝SN：' }}</text>
							<text>{{ item.deviceId }}</text>
						</view>
						<image @click="deleteChooseDevice(item)" class="brief_info_close" src="@/static/icon-close.png" />
					</view>
					<view v-if="currentChooseDeviceType.value == 'device'" class="detail_info">
						<view class="detailTitle">机柜内含充电宝编号</view>
						<view class="powerBankList">
							<view v-for="(singleIdsItem, singleIdsIndex) in item.singleIds" :key="singleIdsIndex" class="powerBankItem">
								{{ singleIdsItem }}
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 选择的充电宝列表 -->
			<view v-if="currentChooseDeviceType.value == 'powerBank' && choosePowerBankList.length > 0" class="choose-list-box">
				<view v-for="(item, index) in choosePowerBankList" :key="index" class="chooseListItem">
					<view class="brief_info" style="margin-bottom: 0">
						<view class="brief_info_text">
							<text>{{ currentChooseDeviceType.value == 'device' ? '机柜SN：' : '充电宝SN：' }}</text>
							<text>{{ item.singleId }}</text>
						</view>
						<image @click="deleteChoosePowerBank(item)" class="brief_info_close" src="@/static/icon-close.png" />
					</view>
				</view>
			</view>

			<!-- 确认下拨按钮 -->
			<view class="allocation_box">
				<view @click="confirm" :class="{ allocation: true, disable: disable }">下拨</view>
			</view>
		</view>
	</view>

	<!-- 设备类型选择 -->
	<cdsPicker v-model="deviceTypeShow" title="设备类型" @confirm="deviceTypeConfirm">
		<template v-slot:body>
			<view class="picker-box">
				<picker-view :value="value" @change="deviceTypeChange" :immediate-change="true" class="picker-view">
					<picker-view-column>
						<view class="pickerItem" v-for="(item, index) in deviceTypeColumns" :key="index">{{ item.text }}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</template>
	</cdsPicker>

	<commonLoading v-model="loadingShow" />
	<commonDialog :dialogShow="dialogShow" dialogTitle="下拨成功" dialogContent="是否继续下拨？" @closeSDialog="closeSDialog" @confirmSDialog="confirmSDialog" :showCloseBtn="false" :closeOnPopstate="false" />
</template>

<script setup>
import { ref } from 'vue';
import { getDeviceAllocationDataCenterData, confirmAllocation } from '@/api/deviceAllocation.js';
import cdsPicker from '@/subPages/components/cds-picker/index.vue';
import commonDialog from '@/components/common-dialog/index.vue';
import { onLoad } from '@dcloudio/uni-app';
import utils from '@/utils/common.js';

onLoad(() => {
	getDeviceAllocationDataCenterDataFun();
});

// 获取选择的巡检员
const chooseInspector = ref({});
uni.$on('chooseInspector', (e) => {
	console.log('选择的巡检员', e);
	chooseInspector.value = e;
});

// 获取选择的设备列表
const chooseDeviceList = ref([]); // 选择的设备列表
const choosePowerBankList = ref([]); // 选择的设备列表
uni.$on('chooseDevice', (e) => {
	console.log('选择的设备', e);
	mapChooseDeviceData.value = [];

	if (currentChooseDeviceType.value.value == 'device') {
		choosePowerBankList.value = [];
		chooseDeviceList.value = e;
		mapChooseDeviceData.value = chooseDeviceList.value.map((device) => {
			return { deviceId: device.deviceId, singleIds: device.singleIds };
		});
	} else if (currentChooseDeviceType.value.value == 'powerBank') {
		chooseDeviceList.value = [];
		choosePowerBankList.value = e;
		mapChooseDeviceData.value = choosePowerBankList.value.map((powerBank) => powerBank.singleId);
	}
});

const mapChooseDeviceData = ref([]); // 选中的设备id列表

// 选择服务商和设备
const deviceTypeShow = ref(false);
const toChoose = (type) => {
	if (type == '巡检员') {
		uni.navigateTo({
			url: '/subPages/inspector/index'
		});
	} else if (type == '设备类型') {
		deviceTypeShow.value = true;
	}
};

// 设备类型选择改变
const deviceTypeColumns = ref([
	{ text: '机柜', value: 'device' },
	{ text: '充电宝', value: 'powerBank' }
]); // 设备类型列表
const currentChooseDeviceType = ref({});
const currentChooseDeviceTypeMap = ref({}); // 用来缓存选择的设备类型结果，不能立即改变设备类型，会导致选择的设备列表显示不正确
const deviceTypeChange = (e) => {
	console.log(e);
	console.log(deviceTypeColumns.value[e.detail.value[0]]);
	currentChooseDeviceTypeMap.value = deviceTypeColumns.value[e.detail.value[0]];
};

// 设备类型选择确认
const deviceTypeConfirm = () => {
	// 没有值，默认选择机柜
	console.log(currentChooseDeviceType.value?.value, '-------------');
	deviceTypeShow.value = false;
	currentChooseDeviceType.value = currentChooseDeviceTypeMap.value;
	if (!currentChooseDeviceType.value?.value) {
		currentChooseDeviceType.value = deviceTypeColumns.value[0];
		choosePowerBankList.value = [];
		mapChooseDeviceData.value = [];
		uni.navigateTo({
			url: `/subPages/allocationDeviceList/index?deviceType=device`
		});
	} else {
		chooseDeviceList.value = [];
		mapChooseDeviceData.value = [];
		uni.navigateTo({
			url: `/subPages/allocationDeviceList/index?deviceType=${currentChooseDeviceType.value?.value}`
		});
	}
};

// 获取下拨数据面板数据
const loadingShow = ref(true);
const AllocationData = ref({});
const updateTime = ref(''); // 更新时间
const getDeviceAllocationDataCenterDataFun = async () => {
	loadingShow.value = true;

	try {
		let res = await getDeviceAllocationDataCenterData();
		if (res.code == 200 && res.data) {
			AllocationData.value = res.data;
		}
	} catch (error) {
		loadingShow.value = false;
	}
	let date = new Date();
	updateTime.value = utils.formatTime(date);
	loadingShow.value = false;
};

// 删除选择的设备
const deleteChooseDevice = (item) => {
	chooseDeviceList.value = chooseDeviceList.value.filter((i) => i.deviceId !== item.deviceId);
	mapChooseDeviceData.value = mapChooseDeviceData.value.filter((i) => i.deviceId !== item.deviceId);
};

// 删除选择的充电宝
const deleteChoosePowerBank = (item) => {
	choosePowerBankList.value = choosePowerBankList.value.filter((i) => i.singleId !== item.singleId);
	mapChooseDeviceData.value = mapChooseDeviceData.value.filter((i) => i !== item.singleId);
};

// 确认下拨
const disable = ref(false);
const dialogShow = ref(false);
const confirm = async () => {
	if (disable.value) return;

	if (!chooseInspector.value.id) {
		uni.showToast({
			title: '请选择巡检员',
			icon: 'none'
		});
		return false;
	}

	if (!currentChooseDeviceType.value.value) {
		uni.showToast({
			title: '请选择设备类型',
			icon: 'none'
		});
		return false;
	}

	if (!mapChooseDeviceData.value.length) {
		currentChooseDeviceType.value.value == 'device'
			? uni.showToast({
					title: '请选择下拨机柜',
					icon: 'none'
			  })
			: uni.showToast({
					title: '请选择下拨充电宝',
					icon: 'none'
			  });
		return false;
	}

	loadingShow.value = true;

	// 根据不同设备类型格式化一下选择的设备数据
	let submitData = {
		inspector: chooseInspector.value.id,
		deviceType: currentChooseDeviceType.value.value == 'device' ? 0 : 1,
		[currentChooseDeviceType.value.value == 'device' ? 'vos' : 'singleIds']: mapChooseDeviceData.value
	};
	
	let res = await confirmAllocation(submitData).catch((err) => {
		loadingShow.value = false;
	});

	if (res.code == 200) {
		loadingShow.value = false;
		dialogShow.value = true;
	}

	loadingShow.value = false;
};

// 关闭继续下拨弹窗
const closeSDialog = () => {
	dialogShow.value = false;
	uni.redirectTo({
		url: '/subPages/home/index'
	})
};

// 继续下拨
const confirmSDialog = () => {
	chooseInspector.value = {};
	chooseDeviceList.value = [];
	choosePowerBankList.value = [];
	mapChooseDeviceData.value = [];
	currentChooseDeviceType.value = {};
	currentChooseDeviceTypeMap.value = {};
	
	dialogShow.value = false;
	getDeviceAllocationDataCenterDataFun();
};

// 跳转到下拨记录
const toAllocationRecord = () => {
	uni.navigateTo({
		url: '/subPages/allocationRecord/index'
	});
};
</script>

<style lang="scss" scoped>
.deviceAllocation-container {
	position: relative;
	height: 100vh;

	.page-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 300px;
	}

	.container-body {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 1100rpx;
		padding: 40rpx 60rpx 240rpx;
		border-radius: 48rpx 48rpx 0 0;
		background-color: #fff;
		overflow-y: scroll;

		.dataBox {
			margin-bottom: 24rpx;

			.dataUpdateTimeBox {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 24rpx;

				.updateTime {
					color: #999;
					font-size: 24rpx;
				}

				.dataTips {
					.icon-help {
						width: 32rpx;
						height: 32rpx;
					}
				}
			}

			.dataInfoBox {
				display: flex;
				align-items: center;
				justify-content: space-between;
				flex-wrap: nowrap;
				color: #999;
				height: 152rpx;
				border-radius: 24rpx;
				padding: 30rpx 24rpx;
				background: linear-gradient(180deg, rgba(62, 217, 121, 0.09) 0%, rgba(255, 255, 255, 0.1) 132.67%);

				.left,
				.right {
					flex: 1;

					.label {
						font-size: 24rpx;

						&::before {
							content: '';
							display: inline-block;
							width: 4rpx;
							height: 16rpx;
							margin-right: 12rpx;
							border-radius: 20rpx;
							background-color: #00c582;
						}
					}

					.testNum {
						color: #333;
						padding-left: 16rpx;
						font-size: 36rpx;
						font-weight: 600;
					}
				}

				.right {
					position: relative;
					padding-left: 24rpx;

					&::before {
						content: '';
						position: absolute;
						top: 50%;
						left: 0;
						transform: translateY(-50%);
						display: inline-block;
						width: 2rpx;
						height: 48rpx;
						background-color: #3ed9793d;
						border-radius: 6rpx;
					}
				}
			}
		}

		.chooseItem {
			margin-bottom: 40rpx;

			.item-title {
				font-family: PingFang SC;
				font-size: 32rpx;
				font-weight: 500;
				line-height: 44rpx;
				color: #333;
				margin-bottom: 24rpx;
			}

			.currentChoose {
				display: flex;
				align-items: center;
				justify-content: space-between;
				height: 104rpx;
				border-radius: 94rpx;
				padding: 0 40rpx;
				overflow: hidden;
				background-color: #f9f9f9;

				.coverText {
					display: inline-block;
					font-family: PingFang SC;
					font-size: 32rpx;
					font-weight: 400;
					line-height: 44rpx;
					color: #999;
					width: 100%;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					padding-right: 40rpx;
				}

				.goIcon {
					width: 10rpx;
					height: 16rpx;
				}
			}
		}

		.choose-list-box {
			.chooseListItem {
				border-radius: 24rpx;
				padding: 24rpx 40rpx;
				background-color: #f9f9f9;
				margin-bottom: 24rpx;

				&:last-child {
					margin-bottom: 48rpx;
				}

				.brief_info {
					display: flex;
					align-items: center;
					justify-content: space-between;
					color: #333;
					font-size: 28rpx;
					margin-bottom: 24rpx;

					.brief_info_close {
						width: 28rpx;
						height: 28rpx;
					}
				}

				.detail_info {
					padding-top: 24rpx;
					border-top: 2rpx solid #e9e9e9;

					.detailTitle {
						color: #333;
						font-size: 24rpx;
						line-height: 16.8px;
						margin-bottom: 24rpx;
					}

					.powerBankList {
						display: grid;
						grid-template-columns: repeat(2, 1fr);

						.powerBankItem {
							color: #333;
							margin-top: 24rpx;
							font-size: 24rpx;

							&:nth-child(1) {
								margin-top: 0;
							}

							&:nth-child(2) {
								margin-top: 0;
							}

							&:nth-child(2n) {
								padding-left: 24rpx;
								border-left: 2rpx solid #e9e9e9;
							}
						}
					}
				}
			}
		}
	}

	.allocation_box {
		position: fixed;
		left: 0;
		bottom: 0;
		display: flex;
		justify-content: center;
		width: 100%;
		height: 120px;
		padding-top: 24px;
		background-color: #fff;

		.allocation {
			display: flex;
			align-items: center;
			justify-content: center;
			width: calc(100vw - 54px);
			height: 49px;
			color: #fff;
			border-radius: 48px;
			font-family: PingFang SC;
			font-size: 16px;
			font-weight: 500;
			line-height: 22.4px;
			background-color: #00c582;
		}

		.disable {
			background-color: #ccc;
		}
	}
}

.picker-box {
	height: 400rpx;
	padding: 0 40rpx;

	.picker-view {
		width: 100%;
		height: 400rpx;

		.pickerItem {
			height: 34px;
			line-height: 34px;
			text-align: center;
		}
	}
}
</style>
